require('../common/style.css')
require('../common/header/index.css');
require('../common/nav-simple/index.css');
require('./index.css');

var $ = require('jquery');

require('../common/header/index.js');
require('../common/nav-simple/index.js');
var _const = require('root/const')
var _user_service = require('service/user-service.js');
var _cart_service = require('service/cart_service.js');

var page = {
    init: function () {
        this.renderHtml();
        this.bindEvent();
    },
    renderHtml: function () {

        _user_service.checkLogin(
            // 已登录
            function (data, msg) {
                _cart_service.cart(
                    function (data, msg) {
                        var len = data.length;
                        var totalPrice = 0;
                        for (let i = 0; i < len; i++) {
                            var templateHtml = $("<div>" +
                                "<div class='cart-item'>" +
                                "<div class='cart-check-wrapper'><input class='cart-item-check' name='check_single' type='checkbox'></div>" +
                                "<img class='main-image'>" +
                                "<p class='cart-name'></p>" +
                                "<p class='price'></p>" +
                                '<div class="count-wrapper">' +
                                '<div class="minus-btn"></div>' +
                                '<input type="number" class="count-input" value="1">' +
                                '<div class="plus-btn"></div>' +
                                "</div>" +
                                "<p class='total'></p>" +
                                "<div class='cart-delete'></div>" +
                                "</div>" +
                                "<div class='clearfix'></div>" +
                                "</div>");
                            templateHtml.find('.cart-item').attr('data-src', 'detail.html?id=' + data[i].productId);
                            if (1 == data[i].checked) {
                                templateHtml.find('.cart-item-check').prop('checked', true);
                                totalPrice = totalPrice + parseFloat(data[i].quantity * parseFloat(data[i].price));
                            }
                            templateHtml.find('.cart-item .main-image').attr("src", _const.good_image_prefix + data[i].mainImage);
                            templateHtml.find('.cart-item .cart-name').text(data[i].productName);
                            templateHtml.find('.cart-item .price').text('￥' + (parseFloat(data[i].price) / 100).toFixed(2));
                            templateHtml.find('.cart-item .count-input').attr("value", data[i].quantity);
                            templateHtml.find('.cart-item .total').text('￥' + (data[i].quantity * parseFloat(data[i].price) / 100).toFixed(2));
                            $('.cart-item-wrapper').append(templateHtml);
                        }
                        $('.pay-info .total-price').text('￥' + (totalPrice / 100).toFixed(2));
                        let num = $("input[name='check_single']:checked").not('.failure').length;
                        $('.count').text(num)
                    },
                    function () { }
                );
            },
            // 未登录
            function (msg) {
                var hintHtml = $("<div>登录后才能看到购物车商品哦~<button class='go-login-btn' onclick=\"window.location.href='user-login.html?redirect=cart.html'\">去登录<button></div></div>")
                $('.cart-wrapper').html(hintHtml)
            }
        );

    },
    bindEvent : function () {
        this.bindAllCheckEvent();
        this.bindToDetailEvent();
        this.bindCountEvent();
        this.bindItemCheckChangeEvent();
        this.bindItemDeleteEvent()
        this.bindPayButton();
    },
    bindAllCheckEvent: function () {
        var that = this;
        $('.cart-check').click(function () {

            if ($(this).is(':checked')) {
                _cart_service.checkAll(
                    function () {
                        $('.cart-check').prop('checked', true);
                        $('.cart-item-check').prop('checked', true);
                        that.updateTotalPrice();
                    },
                    function () {

                    }
                );
            } else {
                _cart_service.unCheckAll(
                    function () {
                        $('.cart-check').prop('checked', false);
                        $('.cart-item-check').prop('checked', false);
                        that.updateTotalPrice();
                    },
                    function () {

                    }
                );

            }

        });
    },
    bindToDetailEvent : function () {
        $('.cart-item-wrapper').on('click', '.main-image, .cart-name', function () {
            var productDetail = $(this).parents('.cart-item').attr('data-src');
            window.open(productDetail);
        });
    },
    bindCountEvent : function () {
        var that = this;
        $('.cart-item-wrapper').on('click', '.minus-btn', function () {
            var thisBtn = $(this);
            var thisCartItem = thisBtn.parents('.cart-item');
            var id = thisCartItem.attr('data-src').replace("detail.html?id=", "");
            var quantity = parseInt(thisBtn.next().val());
            if(quantity > 1) {
                _cart_service.setQuantity(
                    id, 
                    quantity - 1,
                    function (data, msg) {
                        if("OK" == data) {
                            thisBtn.next().val(restrain(quantity - 1));
                        }
                        that.updateCartItemTotalPrice(thisCartItem);
                        that.updateTotalPrice();
                    },
                    function (msg) {
                    }
                );
            }    
        });

        $('.cart-item-wrapper').on('click', '.plus-btn', function () {
            var thisBtn = $(this);
            var thisCartItem = thisBtn.parents('.cart-item');
            var id = thisCartItem.attr('data-src').replace("detail.html?id=", "");
            var quantity = parseInt(thisBtn.prev().val());
            if(quantity < 999) {
                _cart_service.setQuantity(
                    id, 
                    quantity + 1,
                    function (data, msg) {
                        if("OK" == data) {
                            thisBtn.prev().val(restrain(quantity + 1));
                        }
                        that.updateCartItemTotalPrice(thisCartItem);
                        that.updateTotalPrice();
                    },
                    function (msg) {
                    }
                );
            }            
        });

        function restrain(value) {
          if (value < 1) {
            return 1
          };
          if (value > 1000) {
            return 1000;
          }
          return value;
        }
    },
    bindItemCheckChangeEvent : function () {
        var that = this;
        $('.cart-item-wrapper').on('click', '.cart-item-check', function () {
            var thisCheck = $(this);
            var id = thisCheck.parents('.cart-item').attr('data-src').replace("detail.html?id=", "");
            if ($(this).is(':checked')) {
                _cart_service.checkOne(
                    id,
                    function () {
                        thisCheck.prop('checked', true);
                        that.updateTotalPrice()
                    },
                    function () {

                    }
                );
            } else {
                _cart_service.uncheckOne(
                    id,
                    function () {
                        thisCheck.prop('checked', false);
                        that.updateTotalPrice()
                    },
                    function () {

                    }
                );

            }
        });
    },
    bindItemDeleteEvent : function () {

        // var thisCheck = $(this);
        // var id = thisCheck.parents('.cart-item').attr('data-src').replace("detail.html?id=", "");

        var that = this;
        var thisCartItem;
        $('.cart-item-wrapper').on('click', '.cart-delete', function () {
            thisCartItem = $(this).parents('.cart-item');
            that.showDeleteWindow();
        });

        $('.delete-window .confirm-btn').on('click', function () {
            var id = thisCartItem.attr('data-src').replace("detail.html?id=", "");
            _cart_service.deleteOne(
                id,
                function () {
                    that.hideDeleteWindow();
                    that.deleteCartItem(thisCartItem);
                    that.updateTotalPrice();
                },
                function () {
                    console.log("删除失败")
                    // that.hideDeleteWindow();
                }
            );
        });

        $('.delete-window .cancel-btn').on('click', function () {
            that.hideDeleteWindow();
        });
    },
    bindPayButton : function () {
        $('.pay-btn').on('click', function () {
            window.location.href = "checkout.html"; 
        });
    },
    updateTotalPrice : function () {
        console.log("updateTotalPrice")
        _cart_service.getTotalPrice(
            function (data) {
                $('.pay-info .total-price').text('￥' + (data / 100).toFixed(2));
                let num = $("input[name='check_single']:checked").not('.failure').length;
                $('.count').text(num)
            },
            function () {

            }
        );
    },
    showDeleteWindow : function () {
        $('.delete-window-wrapper').css("display", "block"); 
    },
    hideDeleteWindow : function () {
        $('.delete-window-wrapper').css("display", "none"); 
    },
    deleteCartItem : function (thisCartItem) {
        thisCartItem.remove();
    },
    updateCartItemTotalPrice : function (thisCartItem) {
        var id = thisCartItem.attr('data-src').replace("detail.html?id=", "");
        _cart_service.getItemTotalPrice(
            id,
            function (data) {
                console.log(thisCartItem.children('.total').text())
                thisCartItem.children('.total').text('￥' + (data / 100).toFixed(2))
            },
            function () {

            }
        )
    },
    // TODO
    changePayButton : function () {
        var flag = false;    
    }
}

$(function () {
    page.init();
})